package com.stu.spring.context.chapter06.beanfactorpp;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionVisitor;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.StringValueResolver;

import java.util.HashSet;
import java.util.Set;

public class PropertyBlackNameBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

	private Set<String> blackNames;

	public PropertyBlackNameBeanFactoryPostProcessor(){
		this.blackNames = new HashSet<>();
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		String[] beanNames = beanFactory.getBeanDefinitionNames();
		for(String beanName : beanNames){
			BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
			StringValueResolver valueResolver = new StringValueResolver() {
				@Override
				public String resolveStringValue(String strVal) {
					if(isBlack(strVal)){
						return "******";
					}
					return strVal;
				}
			};

			BeanDefinitionVisitor visitor = new BeanDefinitionVisitor(valueResolver);
			visitor.visitBeanDefinition(beanDefinition);
		}
	}

	public boolean isBlack(Object value){
		String upperCase = value.toString();
		return this.blackNames.contains(upperCase);
	}

	public Set<String> getBlackNames() {
		return blackNames;
	}

	public void setBlackNames(Set<String> blackNames) {
		this.blackNames = blackNames;
	}
}
